package com.zhhy.tool.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 短信工具类
 *
 * @author Tellsea
 * @date 2021/05/27
 */
@Slf4j
public class SmsUtils {

	/**
	 * 替换短信模版中的变量
	 *
	 * @param map
	 * @param smsTemplate
	 * @return
	 */
	public static String getMailText(Map<String, String> map, String smsTemplate) {
		//遍历Map中的所有Key，将得到的value值替换模板字符串中的变量值
		Set keys = map.keySet();
		for (Iterator it = keys.iterator(); it.hasNext(); ) {
			String key = String.valueOf(it.next());
			smsTemplate = smsTemplate.replace("${" + key + "}", String.valueOf(map.get(key)));
		}
		return smsTemplate;
	}

	/**
	 * 单条短信发送
	 *
	 * @param baseUrl 路径
	 * @param userid  帐号
	 * @param pwd     密码
	 * @param mobile  发送手机号码
	 * @param content 发送内容
	 * @return
	 * @throws Exception
	 */
	public static String singleSend(String baseUrl, String userid, String pwd, String mobile, String content) throws Exception {
		String strMsg = URLEncoder.encode(content, "GBK");
		//时间戳
		String timestamp = "";
		StringBuilder sb = new StringBuilder();
		sb.setLength(0);
		sb.append("userid=");
		sb.append(userid);
		sb.append("&pwd=");
		sb.append(pwd);
		sb.append("&mobile=");
		sb.append(mobile);
		sb.append("&content=");
		sb.append(strMsg);
		sb.append("&timestamp=");
		sb.append(timestamp);
		sb.append("&svrtype=SMS001&exno=0006");
		log.info("发送单条短信入参：" + sb.toString());
		String result = sendPost(baseUrl + "/v2/std/single_send", sb.toString());
		log.info("发送单条短信出参：" + result);
        /*// 记录日志
        IWmSmsLogService smsLogService = SpringUtils.getBean(IWmSmsLogService.class);
        WmSmsLog smsLog = new WmSmsLog().setReceivePhone(mobile)
                .setSendContent(content)
                .setSendTime(new Date())
                .setSendResult(result);
        JSONObject resultObject = JSONObject.parseObject(result);
        log.info("发送消息返回结果：{}", resultObject.toJSONString());
        if (IntegerUtils.eq(resultObject.getInteger("result"), 0)) {
            smsLog.setIsSuccess(1);
        } else {
            smsLog.setIsSuccess(2);
        }
        smsLogService.save(smsLog);*/
		return result;
	}

	/**
	 * 短信发送
	 *
	 * @param url
	 * @param param
	 * @return
	 */
	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			URLConnection conn = realUrl.openConnection();
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
				"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

			conn.setDoOutput(true);
			conn.setDoInput(true);

			out = new PrintWriter(conn.getOutputStream());
			out.print(param);
			out.flush();
			in = new BufferedReader(
				new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println(e);
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}
}
